昨天介紹了 JWK 之後,今天我們要來實作一個 JWK 範例
初始化私鑰
let encryptPrivateKey = P384.KeyAgreement.PrivateKey()
print("JWK: ", encryptPrivateKey.jwk)
這裡創建了一個 P-384 橢圓曲線的私鑰,並打印其 JWK 表示。
準備要加密的數據
let payload = "Hello world".data(using: .utf8)!
將字符串轉換為 UTF-8 編碼的數據。
創建公鑰 JWK
let publicJwk = JWK(keyType: .ellipticCurve,
key: encryptPrivateKey.publicKey.rawRepresentation,
keyID: "1",
curve: .p384,
x: encryptPrivateKey.jwk.x,
y: encryptPrivateKey.jwk.y)
使用私鑰的公鑰部分創建一個 JWK 對象。
創建 JWE
let jwe = try! JWE(payload: payload,
keyManagementAlg: .ecdhES,
encryptionAlgorithm: .a256GCM,
recipientKey: publicJwk)
使用公鑰 JWK 創建一個 JWE 對象,指定密鑰管理算法和加密算法。
創建私鑰 JWK
let privateJwk = JWK(keyType: .ellipticCurve,
key: encryptPrivateKey.rawRepresentation,
keyID: "1",
curve: .p384,
x: encryptPrivateKey.jwk.x,
y: encryptPrivateKey.jwk.y,
d: encryptPrivateKey.jwk.d)
創建包含私鑰信息的完整 JWK。
解密 JWE
let decrypted = try! jwe.decrypt(recipientKey: privateJwk)
print(jwe.compactSerialization())
print("decryptedString: " , String(data: decrypted, encoding: .utf8)!)
使用私鑰 JWK 解密 JWE,並打印解密後的結果。
6.1. 解密 JWE
let decrypted = try! jwe.decrypt(recipientKey: encryptPrivateKey)
print(jwe.compactSerialization())
print("decryptedString: " , String(data: decrypted, encoding: .utf8)!)
使用私鑰 直接解密 JWE,並打印解密後的結果。
import JSONWebKey
let encryptPrivateKey = P384.KeyAgreement.PrivateKey()
print("JWK: ", encryptPrivateKey.jwk)
let payload = "Hello world".data(using: .utf8)!
let publicJwk = JWK(keyType: .ellipticCurve,
key: encryptPrivateKey.publicKey.rawRepresentation,
keyID: "1",
curve: .p384,
x: encryptPrivateKey.jwk.x,
y: encryptPrivateKey.jwk.y)
print("Custom JWK: ", publicJwk)
let jwe = try! JWE(payload: payload,
keyManagementAlg: .ecdhES,
encryptionAlgorithm: .a256GCM,
recipientKey: publicJwk)
let privateJwk = JWK(keyType: .ellipticCurve,
key: encryptPrivateKey.rawRepresentation,
keyID: "1",
curve: .p384,
x: encryptPrivateKey.jwk.x,
y: encryptPrivateKey.jwk.y,
d: encryptPrivateKey.jwk.d)
let decrypted = try! jwe.decrypt(recipientKey: privateJwk)
print(jwe.compactSerialization())
print("decryptedString: " , String(data: decrypted, encoding: .utf8)!)